#!/usr/bin/python
# -*- coding: utf-8 -*-
import mysql.connector
from mysql.connector.cursor import MySQLCursor


def save_worklog_to_db(config: dict, worklog_list: list) -> int:
    print("开始保存工作日志到JIRA_WORKLOG表……")
    if len(worklog_list) < 1:
        print("工作日志为空，不进行保存")
        return 0
    # 组装SQL及参数
    sql = (
        f"insert into {config['schema']}.jira_worklog (issue_key, issue_type, issue_status, issue_summary, issue_created, issue_updated, issue_reporter, "
        "issue_creator, issue_assignee, issue_desc, id, author, comment, start_time, duration) "
        "values(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) on duplicate key update "
        "issue_status=%s, issue_summary=%s, issue_updated=%s, issue_assignee=%s, issue_desc=%s, comment=%s, start_time=%s, duration=%s"
    )
    values = []
    for worklog in worklog_list:
        issue_desc = worklog['issue_desc'] if len(worklog['issue_desc']) > 0 else None
        comment = worklog['comment'] if len(worklog['comment']) > 0 else None
        values.append((
            # 插入字段
            worklog['issue_key'],
            worklog['issue_type'],
            worklog['issue_status'],
            worklog['issue_summary'],
            worklog['issue_created'],
            worklog['issue_updated'],
            worklog['issue_reporter'],
            worklog['issue_creator'],
            worklog['issue_assignee'],
            issue_desc,
            worklog['id'],
            worklog['author'],
            comment,
            worklog['start_time'],
            worklog['duration'],
            # 更新字段
            worklog['issue_status'],
            worklog['issue_summary'],
            worklog['issue_updated'],
            worklog['issue_assignee'],
            issue_desc,
            comment,
            worklog['start_time'],
            worklog['duration']
        ))

    # 创建数据库连接及游标对象
    db = mysql.connector.connect(host=config['host'], database=config['schema'], user=config['user'], password=config['passwd'])
    cursor: MySQLCursor = db.cursor()

    count = 0
    # 执行批量插入操作
    for value in values:
        print('插入/更新数据：', value)
        cursor.execute(sql, value)
        count += 1

    # 提交更改
    db.commit()
    # 关闭游标和数据库连接
    cursor.close()
    db.close()
    return count
